<?php

namespace app\api\service\event;

use app\api\model\event\Account;
use app\api\model\event\AccountToUser;
use app\api\model\event\Event;
use app\api\model\event\EventGroup;
use app\api\model\event\Material;
use app\api\model\event\Order;
use app\api\model\event\StudyImg;
use app\api\model\template\User;
use app\api\service\template\TemplateService;
use app\api\service\token\LoginToken;
use app\lib\exception\event\CreatorException;
use LinCmsTp5\admin\model\LinUser;
use think\Db;
use think\Exception;

class CreatorService
{
    private static $instance;
    private static $uid;
    private static $gid;

    public static function getInstance(): CreatorService
    {
        $login = LoginToken::getInstance();
        self::$uid = $login->getCurrentUid();
        self::$gid = $login->getCurrentGid();
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    /**
     * @param $params
     * @throws CreatorException
     */
    public function getOrderList($params){
        $pageSize = $params['pageSize']??50;

        $order = Order::field('*')->json(['data'])->with(['product','m_name','a_name','t_num','v_num']);
        if (self::$uid != 1 && self::$gid !=2){
            $order->where("author_id",self::$uid);
        }

        $list = $order->order("id desc")->paginate($pageSize)->each(function($item){
            # 总篇数
            $total_num = 0;
            # 图文总篇数
            $text_num = 0;
            # 视频总篇数
            $video_num = 0;
            foreach ($item->data as $v){
                $arr = (array)$v;
                $total_num+=$arr['num'];
                if ($arr['type'] == 1){
                    $text_num+=$arr['num'];
                }
                if ($arr['type'] == 2){
                    $video_num+=$arr['num'];
                }
            }
            $item->total_num = $total_num;
            $item->text_num = $text_num;
            $item->video_num = $video_num;
            # 已完成
            $item->complete_total_num = count($item->t_num) + count($item->v_num);
            $item->complete_text_num = count($item->t_num);
            $item->complete_video_num = count($item->v_num);
            # 单独平台已写篇数量
            $platform_arr = $this->platformArr($item->id);
            $item->platform_text = $platform_arr[0];
            $item->platform_video = $platform_arr[1];
            unset($item->t_num);
            unset($item->v_num);
            unset($platform_arr);
        });
        return $list;
    }


    /**
     * @param $params
     * @throws CreatorException
     */
    public function getEventList($params){
        $pageSize = $params['pageSize']??50;
        $stat = Event::field("source_platform,count(id)as count")->where("order_id",$params['order_id']);
        $event = Event::field("id,title,app_id,status,type,reason,pub_type,backfill_url,
        view,like,reply,favorite,share,tips,check,create_time,source_platform")
            ->where("order_id",$params['order_id']);
        if (!empty($params['username'])){
            $u_id = LinUser::where('username',$params['username'])->value('id');
            if (!empty($u_id)){
                $event->where('uid',$u_id);
                $stat->where('uid',$u_id);
            }
        }
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $event->where('status',$params['status']);
                $stat->where('status',$params['status']);
            }
        }
        if (isset($params['source_platform'])){
            if ($params['source_platform'] != '') {
                $event->where("source_platform", $params['source_platform']);
                $stat->where("source_platform", $params['source_platform']);
            }
        }
        if (isset($params['view'])){
            if ($params['view'] == 1){
                $event->order("view desc");
            }elseif ($params['view'] == -1){
                $event->order("view asc");
            }

        }
        if (isset($params['reply'])){
            if ($params['reply'] == 1){
                $event->order("reply desc");
            }elseif ($params['reply'] == -1){
                $event->order("reply asc");
            }
        }

        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $event->whereBetweenTime("create_time",$params['start_time'],$params['end_time']);
            $stat->whereBetweenTime("create_time",$params['start_time'],$params['end_time']);
        }
        #所有发布平台
        $total_info = $stat->group("source_platform")->select()->toArray();
        #已回填的所有平台数据
        $part_info = $stat->whereNotNull("backfill_url")->select()->toArray();
        foreach ($total_info as $k=>$v){
            $total_info[$k]['part'] = 0;
            foreach ($part_info as $j){
                if ($v['source_platform'] == $j['source_platform']){
                    $total_info[$k]['part'] = $j['count'];
                    break;
                }
            }
        }
        $list = $event->order("id desc")->paginate($pageSize)->each(function($item){
//            $item->username = LinUser::where('id',$item->uid)->value('username');
            $new_uid = Account::where("app_id",$item->app_id)->value("uid");
            $item->rusername = LinUser::where('id',$new_uid)->value('username');
        });
       $data = [
           "stat"=>$total_info,
           "list"=>$list
       ];
       return $data;
    }



    /**
     * @param $conditions
     * @throws CreatorException
     */
    public function getEventAccountList($conditions){
        $pageSize = $conditions['pageSize']??200;
        $query = Account::field('id,name,platform_id,app_id,uid')->with(['user']);

        if(!empty($conditions['platform_id'])){
            $query = $query->where('platform_id',$conditions['platform_id']);
        }
        $arr = AccountToUser::field("app_id")->where("uid",self::$uid)->select()->toArray();
        $app_arr = [];
        foreach ($arr as $val){
            $app_arr[] = $val['app_id'];
        }
        $query->whereIn("app_id",$app_arr);
        $query->where("in_use",1);
        $list = $query->paginate($pageSize);
        return $list;
    }


    /**
     * @param $params
     * @throws CreatorException
     */
    public function updateEvent($params){
        $event = Event::where("id",$params['id'])->findOrEmpty();
        if ($event->isEmpty()){
            throw new CreatorException([
                'msg' => '作品不存在',
                'error_code' => 20001
            ]);
        }
        if (!empty($params['content_id'])){
            if ($event['content_id'] !=$params['content_id']){
                $check = Event::where("content_id",$params['content_id'])->findOrEmpty();
                if (!$check->isEmpty()){
                    throw new CreatorException([
                        'msg' => '小红书文章已存在',
                        'error_code' => 20005
                    ]);
                }
            }
        }

        DB::startTrans();
        try {
            $params['status'] = 1;
            $event->save($params);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreatorException([
                'msg' => '写作编辑失败',
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws CreatorException
     */
    public function createEvent($params){
        $order = Order::where("id",$params['order_id'])->json(['data'])->where("status",1)->findOrEmpty();
        if ($order->isEmpty()){
            throw new CreatorException([
                'msg' => '订单不存在',
                'error_code' => 20001
            ]);
        }
        if (!empty($params['content_id'])){
            $check = Event::where("content_id",$params['content_id'])->findOrEmpty();
            if (!$check->isEmpty()){
                throw new CreatorException([
                    'msg' => '小红书文章已存在',
                    'error_code' => 20005
                ]);
            }
        }

        $info = [
            "type"=>$params['type'],
            "pub_time"=>$params['pub_time'],
            "order_id"=>$params['order_id'],
            "uid"=>self::$uid,
            "content_id"=>$params['content_id']??null,
            "platform"=>$params['platform']??null
        ];
        if ($params['type'] == 1){
            if (empty($params['images'])){
                throw new CreatorException([
                    'msg' => '图片数组不存在',
                    'error_code' => 20002
                ]);
            }
            $info['images'] = $params['images'];
        }else{
            if (empty($params['url'])){
                throw new CreatorException([
                    'msg' => '视频链接不存在',
                    'error_code' => 20002
                ]);
            }
            $info['url'] = $params['url'];
        }

        $platform_arr = $this->platformArr($params['order_id']);
        if ($info['type'] == 1){
            # 图文
            $event_arr = $platform_arr[0];
        }else{
            # 视频
            $event_arr = $platform_arr[1];
        }

        #计算当前需要撰写的平台
        $platform = [];
        foreach ($order['data'] as $v){
           $arr = (array)$v;
           if ($arr['type'] == $info['type'] && $arr['num'] > 0){
               $key = 1;
               foreach ($event_arr as $k=>$j){
                   if ($arr['name'] == $k && $arr['num'] > $j){
                       $platform[] = $k;
                   }
                   if ($arr['name'] == $k){
                       $key = 2;
                       break;
                   }
               }
               if ($key == 1){
                   $platform[] = $arr['name'];
               }
           }
        }
        if (empty($platform)){
            throw new CreatorException([
                'msg' => '写作类型达到上限',
                'error_code' => 20003
            ]);
        }

        $todayStart= date('Y-m-d 00:00:00', strtotime($params['pub_time']));
        $todayEnd= date('Y-m-d 23:59:59', strtotime($params['pub_time']));
        $is = 0;
        $err = "";
        # 判断账号当日是否超出三次发布
        foreach ($params['data'] as $v){
            $count = Event::where("app_id",$v['app_id'])->whereBetweenTime('pub_time',$todayStart,$todayEnd)->count();
            if ($count>=3){
                $is = 1;
                $err = $v['source_platform'];
                break;
            }
        }
//        if ($is == 1){
//            throw new CreatorException([
//                'msg' => $err."账号发布文章超出上限，清选择其它账号",
//                'error_code' => 20005
//            ]);
//        }

        DB::startTrans();
        try {
            if ($info['type'] == 1){
                Material::where("type",1)->whereIn("url",$info['images'])->setInc("num");
            }else{
                Material::where("url",$info['url'])->setInc('num');
            }
//            $info['status'] $info['status'] = 1;
//            if (self::$uid == 3){
//                $info['status'] = 1;
//            }else{
//                $info['status'] = 0;
//            }
            # 创建任务分组
            if (!empty($platform)){
                $group_id = EventGroup::insertGetId([
                    "title"=>$params['data'][0]['title'],
                    "content"=>$params['data'][0]['content'],
                    "order_id"=>$info['order_id'],
                    "images"=>$info['images']??null,
                    "url"=>$info['url']??null
                ]);
            }
            $push_arr = [];
            foreach ($params['data'] as $val){
                foreach ($platform as $v){
                    if($val['source_platform'] == $v){
                        $u_info = Account::field("uid,pub_type")->where("app_id",$val['app_id'])->find();
//                        $info['pub_type'] = $val['pub_type']??1;
                        $info['pub_type'] = $u_info['pub_type']??1;
                        $info['title'] = $val['title']??null;
                        $info['content'] = $val['content']??null;
                        $info['source_platform'] = $val['source_platform'];
                        $info['app_id'] = $val['app_id'];
                        $info['merchant_id'] = $order['merchant_id'];
                        $info['tags'] = $val['tags']??[];
                        $info['group_id'] = $group_id??0;
                        $info['tips'] = $val['tips']??null;
                        $info['status'] = 1;
                        Event::create($info);

                        if ($u_info['pub_type'] == 2){
                            if(!array_key_exists($u_info['uid'], $push_arr)){
                                $push_arr[$u_info['uid']] = [
                                    "title"=>$val['title']
                                ];
                            }
                        }
                        break;
                    }
                }
            }
            # 推送数组
            foreach ($push_arr as $k=>$val){
                $unionid = LinUser::where("id",$k)->value('unionid');
                if ($unionid){
                    $template = TemplateService::getInstance();
                    $openid = User::where("unionid",$unionid)->value("openid");
                    $data = [
                        "openid"=>[$openid],
                        "miniprogram"=>[
                            "appid"=>"wx343d841e87718665",
                            "pagepath"=>"pages/home/home"
                        ],
                        "data"=>[
                            "first"=>"",
                            "thing6"=> $val['title'],
                            "time5"=>date("Y年m月d日 H:i:s"),
                            "remark"=>""
                        ],
                        "template_id"=>'Lg1kLEU7lS29bMGj_qHOMrqEkc1eOL9oPsefyhmQWsM',
                    ];
                    $template->pushTemplate($data);
                }
            }

            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreatorException([
                'msg' => '写作失败',
                'error_code' => 20004
            ]);
        }

    }

    /**
     * @param $params
     * @throws CreatorException
     */
    public function check($params){
        $event = Event::where('content_id',$params['content_id'])->findOrEmpty();
        if (!$event->isEmpty()){
            throw new CreatorException([
                'msg' => '小红书文章已存在',
                'error_code' => 20001
            ]);
        }
    }

    public function platformArr($order_id,$is_key=1){
        $event_data = Event::where("order_id",$order_id)->field("source_platform,type");
        if ($is_key == 2){
            $event_data->where("status",3);
        }

        $datas = $event_data->select()->toArray();

        $text_platform = [];
        $video_platform = [];
        foreach ($datas as $v){
           if ($v['type'] == 1){
               $text_platform[] = $v['source_platform'];
           }else{
               $video_platform[] = $v['source_platform'];
           }
        }
        $text_platform_arr = [];
        # 图文
        foreach ($text_platform as $v){
            if (empty($text_platform_arr[$v])){
                $text_platform_arr[$v] = 1;
            }else{
                $text_platform_arr[$v]+=1;
            }
        }
        $video_platform_arr = [];
        # 视频
        foreach ($video_platform as $v){
            if (empty($video_platform_arr[$v])){
                $video_platform_arr[$v] = 1;
            }else{
                $video_platform_arr[$v]+=1;
            }
        }


        return array($text_platform_arr,$video_platform_arr);
    }


    /**
     * @param $params
     * @throws CreatorException
     */
    public function getEvent($params){
        $event = Event::where("id",$params['id'])->find();
        return $event;
    }


    /**
     * @param $params
     * @throws CreatorException
     */
    public function deleteEvent($params){
        $event = Event::where("id",$params['id'])->findOrEmpty();
        if ($event->isEmpty()){
            throw new CreatorException([
                'msg' => '文章不存在',
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $event->delete();
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreatorException([
                'msg' => '文章删除失败',
                'error_code' => 20002
            ]);
        }
    }


    /**
     * @param $attrs
     * @throws CreatorException
     */
    public function store($attrs){
        $i = 0;
        if(!empty($attrs)) {
            if (!is_array($attrs)) {
                $attrs = \GuzzleHttp\json_decode($attrs, true);
            }
            // 启动事务
            Db::startTrans();
            try {
                foreach ($attrs as $attr) {
                    $event = Event::where("feed_id",$attr['feed_id'])->findOrEmpty();
                    if ($event->isEmpty()){
                        $group_info = [
                            "title"=>$attr['title'],
                            "content"=>$attr['content'],
                            "images"=>$attr['images']??[],
                            "url"=>$attr['url']??null,
                            "status"=>2,
                            "type"=>1,
                            "order_id"=>58,
                            "sign"=>2
                        ];
                        $group_id = EventGroup::insertGetId($group_info);
                        $info = [
                            "title"=>$attr['title'],
                            "feed_id"=>$attr['feed_id']??null,
                            "content"=>$attr['content'],
                            "images"=>$attr['images']??[],
                            "backfill_url"=>$attr['backfill_url']??null,
                            "view"=>$attr['view']??0,
                            "like"=>$attr['like']??0,
                            "reply"=>$attr['reply']??0,
                            "favorite"=>$attr['favorite']??0,
                            "share"=>$attr['share']??0,
                            "tags"=>$attr['tags']??[],
                            "url"=>$attr['url']??null,
                            "group_id"=>$group_id,
                            "source_platform"=>"逛逛号",
                            "uid"=>1,
                            "merchant_id"=>26,
                            "check"=>1,
                            "pub_type"=>2,
                            "status"=>3,
                            "type"=>1,
                            "order_id"=>58
                        ];
                        $account = Account::field("app_id")
                            ->where("pub_type",2)->where("platform_id",5)
                            ->orderRand()->find();
                        $info['app_id'] =  $account['app_id'];
                        Event::create($info);
                        $i ++;
                    }
                }

                // 提交事务
                Db::commit();
            } catch (Exception $e){
                var_dump($e->getMessage());
                // 回滚事务
                Db::rollback();
                throw new CreatorException([
                    'msg' => '采集失败',
                    'error_code' => 20001
                ]);
            }
        }

        return $i;
    }




    /**
     * @param $params
     * @throws CreatorException
     */
    public function randomStudyImg($params){
        $type = $params['type']??1;
        $data = [];
        Db::startTrans();
        try {
            $cover = StudyImg::field('id,link,title')->where("status", 1)->where("reason", "封面")
                ->lock(true)->orderRand()->find();
            $ids[] = $cover->id;
            $writing = StudyImg::field('id,link')->where("status", 1)->where("reason", "文案")
                ->lock(true)->orderRand()->find();
            $ids[] = $writing->id;
            if ($type == 1){
                $broadcast = StudyImg::field('id,link')->where("status", 1)->where("reason", "直播间")
                    ->lock(true)->orderRand()->find();
                $ids[] = $broadcast->id;
                $data['broadcast'] = $broadcast;
            }

            if ($type == 1){
                if (!$cover || !$writing || !$broadcast){
                    throw new Exception('数据不存在');
                }
            }else{
                if (!$cover || !$writing ){
                    throw new Exception('数据不存在');
                }
            }


            StudyImg::whereIn("id",$ids)->update(['status'=>2,'update_time'=>date("Y-m-d H:i:s")]);
            $data['cover'] = $cover;
            $data['writing'] = $writing;
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreatorException([
                'msg' => "图片无法分配",
                'error_code' => 20001
            ]);
        }
        return $data;
    }
}
